package com.example.demo.controller;

import cn.hutool.core.util.IdUtil;
import com.example.demo.entity.*;
import com.example.demo.entity.dto.OrderCreateInput;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.sql.JSqlClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JSqlClient sqlClient;

    private static final OrderFetcher ORDER_FETCHER = OrderFetcher.$
            .allScalarFields()
            .items(
                    OrderItemFetcher.$.allScalarFields()
            );


    @PostMapping("create")
    public void create(@RequestBody OrderCreateInput orderCreateInput) {

        Order entity = orderCreateInput.toEntity();

        entity = OrderDraft.$.produce(entity, orderDraft -> {
            orderDraft.setOrderNo(IdUtil.getSnowflakeNextIdStr());
            orderDraft.setStatus(OrderStatus.Pending);
        });


        sqlClient.save(entity);
    }

    @GetMapping("list")
    public List<@FetchBy("ORDER_FETCHER") Order> list() {
        return sqlClient.getEntities().findAll(ORDER_FETCHER);
    }
}
